package com.ruoyi.job.task;

import com.ruoyi.job.util.EmailUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Component("pyTask")
public class PyTask {
    public void getRoot() {
        pyTask("");
    }

    public void weeklyJob() {
        pyTask("/py/weekly/update");
    }

    public void dailyJob() {
        pyTask("/py/daily/update");
    }

    private void pyTask(String urlString) {
        String msg;
        String status = null;
        String subject;

        try {
            // 1. 调用FastAPI
            URL url = new URL("http://127.0.0.1:8000" + urlString); // 替换为实际的API URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 2. 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                JSONObject jsonResponse = getJsonObject(connection);
                try {
                    status = jsonResponse.getString("status");
                    msg = jsonResponse.getString("message");
                } catch (JSONException e) {
                    msg = "json解析异常。" + e;
                }
            } else {
                msg = "请求失败，响应码: " + responseCode;
            }

        } catch (Exception e) {
            msg = "请求过程中发生错误。" + e.getMessage();
        }

        if (status != null && status.equals("success")) {
            subject = "PyTask定时任务正常运行";
        } else {
            subject = "PyTask定时任务出现异常";
        }

        System.out.println(subject);
        System.out.println(msg);

        // 4. 通过邮件发送结果
        try {
            EmailUtils.sendEmail(subject, msg);
        } catch (Exception e) {
            System.err.println("邮件发送失败: " + e.getMessage());
        }
    }

    private static JSONObject getJsonObject(HttpURLConnection connection) throws IOException {
        StringBuilder responseContent = new StringBuilder();

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseContent.append(inputLine);
            }
        }

        // 3. 解析JSON响应
        return new JSONObject(responseContent.toString());
    }
}
